package us.kg.kotoriforest.spring.tx.dao;

import lombok.AllArgsConstructor;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import us.kg.kotoriforest.spring.tx.pojo.Book;

/**
 * @author Kotori rotroutine@163.com
 * @since 2025/1/31
 */
@Repository
@AllArgsConstructor
public class BookDao {
    private JdbcTemplate jdbcTemplate;

    public Book getBookById(int id) {
        String sql = "SELECT * FROM book WHERE id = ?";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Book.class), id);
    }

    public int addBook(Book book) {
        String sql = "INSERT INTO book (bookName, price, stock) VALUES (?, ?, ?)";
        return jdbcTemplate.update(sql, book.getBookName(), book.getPrice(), book.getStock());
    }

    public int decreaseBookStock(int id, int delta) {
        String sql = "UPDATE book SET stock = stock - ? WHERE id = ?";
        return jdbcTemplate.update(sql, delta, id);
    }

    public int deleteBookById(int id) {
        String sql = "DELETE FROM book WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }
}
